<!-- 
 * 科技政策组件
 * @author: 
 * @since: 2022-06-08
 * index.vue
-->
<template>
  <div class="scienceTechnology-com-container p20 detailsPageBox">
    <div class="detailsMain" id="pdfDom">
      <div class="title">基本信息</div>
      <div class="form">
        <el-form :model="form" :rules="rules" ref="validateForm">
          <el-row>
            <el-col :span="8">
              <el-form-item label="政策标题：" v-if="props.isType === 3" class="detailLabel detail-form-item">
                <div class="detailWord">{{ form.title }}</div>
              </el-form-item>
              <el-form-item label="政策标题：" prop="title" v-else class="detail-form-item">
                <el-input v-model="form.title" placeholder="请输入政策标题" clearable />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="原文链接：" v-if="props.isType === 3" class="detail-form-item detailLabel">
                <div class="detailWord">{{ form.url }}</div>
              </el-form-item>
              <el-form-item label="原文链接：" prop="url" v-else class="detail-form-item">
                <el-input v-model="form.url" placeholder="请输入原文链接" clearable />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label="发文部门：" v-if="props.isType === 3" class="detail-form-item detailLabel">
                <div class="detailWord">{{ form.source }}</div>
              </el-form-item>
              <el-form-item label="发文部门：" prop="source" v-else class="detail-form-item">
                <el-input v-model="form.source" placeholder="请输入发文部门" clearable />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="发文端口：" v-if="props.isType === 3" class="detail-form-item detailLabel">
                <div class="detailWord">{{ form.sendPortName }}</div>
              </el-form-item>
              <el-form-item label="发文端口：" prop="sendPortId" v-else class="detail-form-item">
                <el-select v-model="form.sendPortId" placeholder="请选择" @change="selectPort">
                  <el-option :label="item.keyName" :value="item.keyId" v-for="(item, index) in state.messagePortList" :key="index" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label="发布日期：" v-if="props.isType === 3" class="detail-form-item detailLabel">
                <div class="detailWord">{{ form.publishDate }}</div>
              </el-form-item>
              <el-form-item label="发布日期：" prop="publishDate" v-else class="detail-form-item">
                <el-date-picker v-model="form.publishDate" type="date" placeholder="请选择" format="YYYY/MM/DD" value-format="YYYY-MM-DD" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="政策类型：" v-if="props.isType === 3" class="detail-form-item detailLabel">
                <div class="detailWord">{{ form.policyTypeName }}</div>
              </el-form-item>
              <el-form-item label="政策类型：" prop="policyType" v-else class="detail-form-item">
                <el-select v-model="form.policyType" placeholder="请选择" @change="v=>{form.policyType = v}">
                  <el-option :label="policy" :value="policyKey" v-for="(policy, policyKey) in state.policyTypeList" :key="policyKey" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="政策正文：" v-if="props.isType === 3" class="detail-form-item detailLabel">
                <div class="detailWord" v-html="form.content"></div>
              </el-form-item>
              <el-form-item label="政策正文：" prop="content" v-else class="detail-form-item">
                <TextEditor @textEdit="textEdit" :html="form.content"></TextEditor>
              </el-form-item>
            </el-col>
            <el-col :span="24" v-if="props.isType === 3 && form.keywords.length > 0">
              <el-form-item label="政策关键词：" class="policyKeywordDetails detail-form-item detailLabel">
                <el-tag v-for="tag in form.keywords" :key="tag" :disable-transitions="false">
                  {{ tag }}
                </el-tag>
              </el-form-item>
            </el-col>
            <el-col :span="24" v-if="props.isType !== 3">
              <el-form-item label="" label-width="82px" class="detail-form-item">
                <div class="keyword">
                  <el-button type="primary" @click="smartKeyword">生成关键词</el-button>
                  <el-button class="add" @click="customAddKeyword">+添加政策关键词</el-button>
                  <div class="tags" v-if="form.keywords.length > 0">
                    <span class="title">政策关键词</span>
                    <el-tag v-for="(tag, index) in form.keywords" :key="tag" class="tag-item" closable :disable-transitions="false" @close="delTag(index)">
                      {{ tag }}
                    </el-tag>
                  </div>
                </div>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24" class="upload">
              <el-form-item label="附件上传：" class="detail-form-item detailLabel" v-if="props.isType === 3 && state.file.length > 0">
                <div class="file-box">
                  <div class="file-item" v-for="(item, index) in state.file" :key="index" @click="clickFile(item)">
                    <div class="icon">
                      <i v-if="item.fileSuffix === 'docx'" class="iconfont icon-word1" :style="{ color: '#4f95f4' }"></i>
                      <i v-if="item.fileSuffix === 'xlsx'" class="iconfont icon-drive-ms-excel" :style="{ color: '#26c083' }"></i>
                      <i v-if="item.fileSuffix === 'pdf'" class="iconfont icon-pdf" :style="{ color: '#f16664' }"></i>
                    </div>
                    <div class="info">
                      <div class="name">{{ item.name }}</div>
                      <div class="size">{{ item.fileSize }}MB</div>
                    </div>
                  </div>
                </div>
              </el-form-item>
              <el-form-item label="附件上传：" class="detail-form-item addEditPpload" v-if="props.isType !== 3" :required="true">
                <el-upload class="upload-box" action="#" :http-request="upload" :limit="5" multiple :before-remove="delUpload" :file-list="state.file" accept=".doc,.docx,.xls,.xlsx,.pdf," :on-preview="clickFile" :on-exceed="handleExceed" :auto-upload="false">
                  <el-button type="primary">请选择文件</el-button>
                  <span class="tip">（最大10M，文件格式Word、Excel、PDF，最多上传5个）</span>
                </el-upload>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row v-if="props.isType !== 3">
            <el-col :span="6">
              <el-form-item label="是否启用：" prop="valid" :required="true" class="noRules detail-form-item">
                <el-radio-group v-model="form.valid">
                  <el-radio :label="item.label" v-for="(item, index) in radioList" :key="index">{{ item.value }}</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <!-- <el-col :span="6">
              <el-form-item label="是否热门：" prop="isHot" :required="true" class="noRules detail-form-item">
                <el-radio-group v-model="form.isHot">
                  <el-radio :label="item.label" v-for="(item, index) in radioList" :key="index">{{ item.value }}</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col> -->
            <el-col :span="6">
              <el-form-item label="是否推荐：" prop="isRecommend" :required="true" class="noRules detail-form-item">
                <el-radio-group v-model="form.isRecommend">
                  <el-radio :label="item.label" v-for="(item, index) in radioList" :key="index">{{ item.value }}</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
    </div>
    <div class="detailsHandleBtn">
      <el-button type="primary" size="mini" @click="submit" v-if="props.isType !== 3">提交</el-button>
      <el-button size="mini" @click="reset" v-if="props.isType !== 3">重置</el-button>
      <el-button type="primary" size="mini" v-else v-print="'#pdfDom'">导出pdf</el-button>
    </div>
    <el-dialog v-model="isShowCustomAddDialog" title="" width="420px" :before-close="closeCustomAdd">
      <div>请输入政策关键词</div>
      <div class="input">
        <el-input v-model="state.policyKeyword" clearable />
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="closeCustomAdd">取消</el-button>
          <el-button type="primary" @click="confirmCustomAdd">确定</el-button>
        </span>
      </template>
    </el-dialog>
    <div class="keywordDialog">
      <el-dialog v-model="isShowSmartAddDialog" title="科技政策关键词选择" width="600px" :before-close="closeSmartAdd">
        <div class="tip">系统根据您的政策正文，自动匹配了以下关键词，请选择合适的关键词哦~</div>
        <el-checkbox-group v-model="state.smartSelectKeyword">
          <el-checkbox :label="item" v-for="(item, index) in state.smartKeywordList" :key="index" />
        </el-checkbox-group>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="closeSmartAdd">取消</el-button>
            <el-button type="primary" @click="confirmSmartAdd">添加</el-button>
          </span>
        </template>
      </el-dialog>
    </div>
    <LoadingAnimation v-if="loading"></LoadingAnimation>
  </div>
</template>

<script setup>
import { onMounted, ref, reactive, defineProps, computed } from 'vue';
import { policyAddApi, policyEditApi, getPolicyDetailsByIdApi, getFileFlowByIdApi, delFileApi, getPolicyTypeApi} from '@/api/interface/policy.js'
import { successHandle, fileDownload, fileDel, detailHandleFinish } from '@/utils/common.js'
import { sessionstorage } from '@/utils/storage.js'
import { ElMessage } from 'element-plus'
import { getDictItemListApi } from '@/api/interface/dict.js'
import { textToKeywordsApi } from '@/api/interface/algorithm.js'



const props = defineProps({
  isType: {
    type: Number,
    default: 1,//1.新增 2.编辑
  }
})

const form = reactive({
  id: '',
  title: '',//政策标题
  url: '',//原文链接
  source: '',//发文部门
  sendPortId: '',//发文端口id
  sendPortName: '',//发文端口name
  publishDate: '',//发布日期
  policyType:'',
  content: '',//政策正文
  policyTypeName:"",
  valid: true,//是否启用
  //   isHot: true,//是否热门
  isRecommend: true,//是否推荐
  keywords: [],//关键词
})

const loading = ref(false)


const state = reactive({
  policyKeyword: '',//政策关键词
  messagePortList: [],//发文端口列表
  smartKeywordList: [],//智能关键词列表
  smartSelectKeyword: [],//智能关键词选择列表
  file: [],//文件
  policyItem: {},
  policyTypeList: [],
})

//是否打开自定义添加政策关键词弹窗
const isShowCustomAddDialog = ref(false)
//是否打开智能添加政策关键词弹窗
const isShowSmartAddDialog = ref(false)

//单选列表
const radioList = reactive([
  {
    label: true,
    value: '是'
  },
  {
    label: false,
    value: '否'
  }
])

//政策类型字典
const getPolicyType = () => {
  getPolicyTypeApi().then(res => {
    state.policyTypeList = res.data
  })
}
getPolicyType()

//form表单
const validateForm = ref(null)

//表单验证 
const rules = {
  title: [{ required: true, message: '必填项', trigger: 'blur' }],
  url: [{ required: true, message: '必填项', trigger: 'blur' }],
  source: [{ required: true, message: '必填项', trigger: 'blur' }],
  sendPortId: [{ required: true, message: '必选项', trigger: ['change', 'blur'] }],
  policyType: [{ required: true, message: '必选项', trigger: ['change', 'blur'] }],
  publishDate: [{ required: true, message: '必选项', trigger: 'blur' }],
  content: [{ required: true, message: '必填项', trigger: 'blur' }],
};


onMounted(() => {
  getDictItemList()
  if (props.isType !== 1) {//编辑
    state.policyItem = sessionstorage.get('policyItem')
    getPolicyDetailsById()

  }

})
//点击文件
const clickFile = (file) => {
  if (file.id) {
    getFileFlowById(file)
  }
}

//通过附件id获取文件流
const getFileFlowById = (file) => {
  const params = {
    fileId: file.id
  }
  getFileFlowByIdApi(params).then(res => {
    fileDownload(file, res)
  })
}
//通过id获取详情
const getPolicyDetailsById = () => {
  const params = {
    id: state.policyItem.id
  }
  getPolicyDetailsByIdApi(params).then(res => {
    const { status, data } = res
    if (status === 200) {
      for (let key in form) {
        form[key] = data[key]
        if (key === "sendPortId") {
          form[key] = Number(data[key])
        }
        if (key === 'content') {
          form[key] = `<div>${data[key]}</div>`
        }
      }
      state.file = data.file.map(item => ({
        ...item,
        name: item.fileShowname
      }))
    }
  })
}



// 文件数量过多时提醒
const handleExceed = () => {
  ElMessage({
    message: '最多支持5个附件上传',
    type: 'warning',
  })
}

//获取发文端口数据
const getDictItemList = () => {
  const params = {
    ipi: 1,
    ips: 100,
    dictType: 'DICT_SEND_PORT'
  }
  getDictItemListApi(params).then(res => {
    const { status, data } = res
    if (status === 200) {
      state.messagePortList = data.result
    }
  })

}
//根据文本生成关键词
const getTextToKeywords = () => {
  loading.value = true
  const params = {
    data: form.content,
  }
  textToKeywordsApi(params).then(res => {
    const { status, data } = res
    if (status === 200) {
      loading.value = false
      state.smartKeywordList = data.keyword
      isShowSmartAddDialog.value = true
    }
  }).catch(() => {
    loading.value = false

  })

}

//点击智能生成关键词
const smartKeyword = () => {
  if (form.content === '<p><br></p>' || !form.content) {
    ElMessage({
      message: '请填写政策正文',
      type: 'warning',
    })
  } else {
    getTextToKeywords()

  }
}
//添加智能匹配关键词确认
const confirmSmartAdd = () => {
  if (state.smartSelectKeyword.length > 0) {
    form.keywords = [...form.keywords, ...state.smartSelectKeyword]
    closeSmartAdd()
  } else {
    ElMessage({
      message: '至少选择一个',
      type: 'warning',
    })
  }
}

//上传
const upload = (fileData) => {
  const { file } = fileData

}
//删除文件
const delUpload = (file, fileList) => {
  fileDel(file, fileList, props.isType, () => {
    const params = {
      fileId: file.id,
      bucket: file.bucket
    }
    delFileApi(params).then(res => {
      successHandle(res)
      getPolicyDetailsById()
    })

  }, (data) => {
    state.file = data
  })

}

//获取政策正文
const textEdit = (text, type) => {
  form.content = text;

}
//关闭智能添加政策关键词弹窗
const closeSmartAdd = () => {
  isShowSmartAddDialog.value = false
  state.smartSelectKeyword = []

}

//打开自定义添加政策关键词弹窗
const customAddKeyword = () => {
  isShowCustomAddDialog.value = true
}

//关闭自定义添加政策关键词弹窗
const closeCustomAdd = () => {
  isShowCustomAddDialog.value = false
  state.policyKeyword = ''
}
//确定自定义添加政策关键词
const confirmCustomAdd = () => {
  if (!state.policyKeyword) {
    ElMessage({
      message: '必填项',
      type: 'warning',
    })
  } else {
    form.keywords.push(state.policyKeyword)
    closeCustomAdd()
  }

}

//删除tag
const delTag = (index) => {
  form.keywords.splice(index, 1)
}
//选择发文端口
const selectPort = (value) => {
  state.messagePortList.forEach(item => {
    if (item.keyId === value) {
      form.sendPortName = item.keyName
    }
  })
}


//提交
const submit = () => {
  validateForm.value.validate((valid) => {
    if (valid) {
      if (form.content === '<p><br></p>') {
        ElMessage({
          message: '请填写政策正文',
          type: 'warning',
        })

      } else {
        const formData = new FormData();
        state.file.forEach(item => {
          if (item.raw) {
            formData.append('file', item.raw)

          }

        })
        formData.append('form', new Blob([JSON.stringify(form)], { type: 'application/json' }))
        if (form.id) {//编辑
          policyEditApi(formData).then(res => {
            detailHandleFinish(res, 'Policy')

          })
        } else {//新增
          policyAddApi(formData).then(res => {
            detailHandleFinish(res, 'Policy')
          })
        }

      }
    } else {
      console.log('没通过验证');
    }
  });
}

//重置
const reset = () => {
  if (props.isType === 2) {//编辑
    getPolicyDetailsById()
  } else {
    validateForm.value.resetFields()
    form.content = ''
    form.keywords = []
    state.file = []
  }
}


</script>

<style lang="scss" scoped>
#pdfDom {
  .title {
    font-size: 16px;
    font-weight: bold;
    color: #333;
    margin-bottom: 30px;
  }
  .detailLabel {
    :deep(.el-form-item__label) {
      padding: 0 !important;
    }
  }
  .policyKeywordDetails {
    .el-tag {
      margin-right: 5px;
    }
  }
  .file-box {
    width: 100%;
    .file-item {
      width: 100%;
      background: #f5f7fd;
      border-radius: 4px;
      display: flex;
      align-items: center;
      margin-bottom: 10px;
      cursor: pointer;
      .icon {
        margin: 0 20px;

        i {
          font-size: 28px;
        }
      }
      .info {
        div {
          color: #333;
          &:first-child {
            font-weight: bold;
            font-size: 14px;
          }
          &:last-child {
            font-size: 12px;
          }
        }
      }
    }
  }
}
.scienceTechnology-com-container {
  .upload {
    :deep(.el-form-item__content) {
      width: 100%;
    }
    .upload-box {
      width: 100%;
    }
  }

  .form-btn {
    :deep(.el-form-item__label) {
      visibility: hidden;
    }
    .el-button {
      width: 100px;
    }
  }
  .keyword {
    display: flex;
    .add {
      background: #25d390;
      color: #fff;
      border: none;
    }
    .tags {
      margin-left: 10px;
      .title {
        font-weight: bold;
        font-size: 12px;
        color: #333;
        margin-right: 10px;
      }
      .tag-item {
        margin-right: 10px;
      }
    }
  }
  .el-dialog__body {
    .input {
      padding-top: 15px;
    }
    .tip {
      color: #666;
      font-size: 12px;
      margin-bottom: 30px;
    }
  }
  .upload-box {
    .tip {
      color: #f74b33;
      font-size: 12px;
    }
  }
  .el-checkbox {
    width: calc((100% - 5px * 3) / 3);
    margin-right: 5px;
    :deep(.el-checkbox__label) {
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }
  }
  .keywordDialog {
    :deep(.el-dialog__body) {
      padding: 0 20px 20px 20px !important;
    }
  }
  :deep(.detailWord) {
    font-size: 12px;
    color: #333;
    p {
      margin: 0;
    }
  }

  .addEditPpload {
    :deep(.el-form-item__label) {
      &::before {
        visibility: hidden;
      }
    }
  }
}
</style>
